<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/views/include/taglib.jsp" %>
<%@ taglib prefix="his_fns" uri="/WEB-INF/tlds/his_fns.tld" %>
<div class="app">
    <section class="layout">
        <section class="main-content col-lg-12" id="stcokLeftDiv">
            <div class="content-wrap">
                <div class="wrapper" style="bottom: 50px;">
                    <ul class="nav nav-tabs">
                        <li class="active">
                            <a href="#" onclick="loadDiv('mainCenterDiv','${ctx}/csm/expStock/index')">入库处理</a>
                        </li>
                    </ul>
                    <section class="panel panel-default">
                        <div class="panel-body">
                            <div class="table-responsive no-border">
                                <div class="datatable-top">
                                    <div class="pull-left">
                                        <form:form id="searchForm" modelAttribute="expStock"
                                                   onsubmit="return loadDivForm('mainCenterDiv','searchForm','${ctx}/csm/expStock/index');"
                                                   method="post" class="form-inline">
                                            <div class="form-group">
                                                <label class=" control-label">入库类别：</label>
                                                <form:select path="expImportMaster.importClass" id="masterClassId" htmlEscape="false" class="form-control" maxlength="1"
                                                             onchange="loadSupplier()" data-parsley-required="true">
                                                    <form:options items="${his_fns:getImpOrOutpList('1')}" itemLabel="inOutName" itemValue="type" htmlEscape="false" />
                                                </form:select>
                                            </div>
                                            <div class="form-group">
                                                <label class=" control-label">供货方：</label>
                                                <form:select path="supplier" id="supplier" htmlEscape="false" class="form-control" data-parsley-required="true">
                                                </form:select>
                                            </div>
                                            <div class="form-group">
                                                <label class=" control-label">日期：</label>
                                                <input name="importDate" id="startDate1" htmlEscape="false" readonly class="form-control Wdate" data-parsley-required="true" readonly onfocus="WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss'})" value='<fmt:formatDate value="${expPrice.startDate}" pattern="yyyy-MM-dd HH:mm:ss"/>'/>
                                            </div>
                                            <div class="form-group">
                                                <label class=" control-label">入库金额总计：</label>
                                                <input class="form-control" id="totalMoney" type="text" readonly>
                                            </div>
                                            <div class="form-group">
                                                <label class=" control-label">付款方式：</label>
                                                <form:select path="accountType" id="accountType" class="form-control"  >
                                                    <form:option value="" label="" />
                                                    <form:options items="${fns:getDictList('ACCOUNT_TYPE')}" itemLabel="label" itemValue="value" htmlEscape="false" />
                                                </form:select>
                                            </div>
                                            <script>
                                                $(function(){
                                                    $("#masterClassId").change(function(){
                                                        if($(this).val()=='0'){
                                                            $("#accountType").attr('data-parsley-required','true');
                                                        }
                                                        else{
                                                            $("#accountType").attr('data-parsley-required','false');
                                                        }
                                                    })
                                                })
                                            </script>
                                            <div class="form-group">
                                                    <input id="btnSubmit" class="btn btn-primary" type="button" onclick="saveImport()" value="保存"/>
                                                    <input id="addExp" class="btn btn-primary" type="button" value="增加" onclick="addExpList()"/>
                                            </div>
                                        </form:form>
                                    </div>
                                </div>
                                <table id="contentTable" class="table table-bordered table-striped mg-t datatable">
                                    <thead>
                                    <tr>
                                        <th hidden>jsonText</th>
                                        <th>品名</th>
                                        <th>型号</th>
                                        <th hidden="hidden">包装数量</th>
                                        <th>规格</th>
                                        <th hidden="hidden">单位代码</th>
                                        <th>单位</th>
                                        <th hidden="hidden">最小规格</th>
                                        <th hidden="hidden">最小单位代码</th>
                                        <th hidden="hidden">最小单位</th>
                                        <th>厂家</th>
                                        <th>进货价</th>
                                        <th>批号</th>
                                        <th>有效期</th>
                                        <th>灭菌方式</th>
                                        <th>灭菌批号</th>
                                        <th>灭菌日期</th>
                                        <th>入库数量</th>
                                        <th>金额</th>
                                        <th>操作</th>
                                    </tr>
                                    </thead>
                                    <tbody>
                                </table>
                            </div>
                        </div>
                    </section>
                </div>
            </div>
        </section>

        <%--右侧消耗品规格字典列表--%>
        <section class="main-content col-lg-4" style="display: none" id="stcokRightDiv">
            <div class="content-wrap" id="rigthCenterDiv">
            </div>
        </section>
    </section>
</div>
<script type="text/javascript">
    loadSupplier();
    function loadSupplier() {
        $("#supplier").html("");  //供货单位
        var importClassValue = $('#masterClassId').val();  //入库类别 代码
//        var importClassName = $('#masterClassId option:selected').text();//入库类别 名称
        if($.trim(importClassValue) == '3'){  //退货
            toastr.error('退货入库请到批量入库页面操作!');
            return false;
        }
        $.ajax({
            url: '${ctx}/csm/expSupplierCata/getSupplierOrStorageList?inoutType=' + '1' + '&type=' + importClassValue,
            type: 'get',
            contentType: 'application/json',
            async: true,
            success: function (data, textStatus, jqXHR) {
                if (data.length > 0) {
                    if (typeof(data[0].supplierJc) == 'undefined') {
                        $.each(data, function (index, item) {
                            $("#supplier").append("<option value=''></option>");
                            $("#supplier").append("<option value='" + item.storageCode + "'>" + item.storageName + "</option>");
                        });
                    } else {
                        $.each(data, function (index, item) {
                            $("#supplier").append("<option value=''></option>");
                            $("#supplier").append("<option value='" + item.id + "'>" + item.supplierJc + "</option>");
                        });
                    }
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {

            }
        });
    }
    /*库存单位补全*/
    autoCompleteFirm();
    function autoCompleteFirm(inputId){
        var url="${ctx}/csm/expStorageDept/findByMasterClass";
        $("#supplier").autocomplete(url, {
            minChars: 0, //在触发autoComplete前用户至少需要输入的字符数.
            max: 20,//autoComplete下拉显示项目的个数
            autoFill: false, //要不要在用户选择时自动将用户当前鼠标所在的值填入到input框
            //mustMatch: true, //autoComplete只会允许匹配的结果出现在输入框,所有当用户输入的是非法字符时将会得不到下拉框
            matchContains: true, //决定比较时是否要在字符串内部查看匹配,如ba是否与foo bar中的ba匹配.使用缓存时比较重要.不要和autofill混用
            multipleSeparator: '',//如果是多选时,用来分开各个选择的字符.
            multiple: false, //是否允许输入多个值即多次使用autoComplete以输入多个值
            scrollHeight: 300,
            width: "20%",
            dataType: 'json',
            method: 'POST',
            onBegin: function(options) { //修改--用于动态改变ledger的值
                options.extraParams.masterClass= $('#masterClassId').val();
                return options;
            },
            parse:  function(data){
                var rows = [];
                for(var i=0; i<data.length; i++){
                    rows[rows.length] = {
                        data:data[i],
                        value:data[i].id,
                        result:data[i].storageName
                    };
                }
                return rows;
            }, formatItem: function(data, i, max){
                return data.storageName;
            }
        }).result(function(event,data,formatted){
            $('#storageFrom').attr('value',data.id);
        });
    }
    //弹出右边增加消耗品框
    function addExpList(){
        $("#stcokLeftDiv").attr("class","main-content col-lg-8");
        $("#stcokRightDiv").show('normal');
        loadDiv('rigthCenterDiv','${ctx}/csm/expStock/form');
        $("#remarks").attr("readonly","false");
        $("#minUnits_change").css("display","none");
        $("#packageUnits_change").css("display","none");
        $("#packageUnits_add").show('normal');
        $("#minUnits_add").show('normal');
    }

    //删除一行消耗品
    function removeList(btn){
        $(btn).parent().parent().remove();
        totalPrice();
    }
    //设置出库日期为当前时间,不能编辑
    var date = new Date();
    var nowMonth = "";
    if(date.getMonth()+1 <= 9){
        nowMonth = "0" + (date.getMonth() + 1) + "";
    }else{
        nowMonth = (date.getMonth() + 1) + "";
    }
    var hours = "";
    if(date.getHours() < 10){
        hours = "0" + date.getHours();
    }else{
        hours = date.getHours();
    }
    var minutes = "";
    if(date.getMinutes() < 10){
        minutes = "0" + date.getMinutes();
    }else{
        minutes = date.getMinutes();
    }
    var seconds = "";
    if(date.getSeconds() < 10){
        seconds = "0" + date.getSeconds();
    }else{
        seconds = date.getSeconds();
    }
    var now = date.getFullYear() + "-" + nowMonth + "-" + date.getDate() + " " + hours + ":" + minutes + ":" + seconds;
    $('#startDate1').val(now);
    //入库金额总计
    $('#totalMoney').val(0.00);
    //修改消耗品
    function updateList(btn){
        var td = $(btn).parent().parent().children().eq(0).text();
        $("#stcokLeftDiv").attr("class","main-content col-lg-8");
        $("#stcokRightDiv").show('normal');
        $("#remarks").attr("readonly","true");
        $("#minUnits_change").show('normal');
        $("#packageUnits_change").show('normal');
        $("#packageUnits_add").css("display","none");
        $("#minUnits_add").css("display","none");
        fillForm($("#inputForm"),td);
        $(btn).parent().parent().remove();
        totalPrice();
    }

    function totalPrice(){
        var list=$("table tr").find("td:eq(19)");
        var price=0;
        for (var i=0;i<list.length;i++){
            price+=parseFloat(list[i].innerText);
        }
        $('#totalMoney').val(price);
    }

    function saveImport(){
        var supplier= $('#supplier').val();
        if(supplier==null || supplier=="" || typeof(supplier) == 'undefined'){
            toastr.error('请选择供货单位');
        }
        else if($("#masterClassId").val()=='0'&&$("#accountType").val()==''){
                toastr.error('请选择付款方式');
        }
        else{
            var list=$("table tr").find("td:eq(0)");
            var dataList=[];
            var data={};
            for (var i=0;i<list.length;i++){
                data=jQuery.parseJSON( list[i].innerText );
                data.storageFrom=$('#storageFrom').val();
                data.importClass=$('#masterClassId').val();
//                data.importDate=$('#startDate1').val();
                data.accountType=$('#accountType').val();
                data.supplier=$('#supplier').val();
                dataList.push(data);
            }

            var dataListJson = JSON.stringify(dataList);
            if(dataListJson==null ||dataListJson==""){
                toastr.error('请添加要入库的消耗品');
            }else{
                $.ajax({
                    type: "POST",
                    url: '${ctx}/csm/expStock/importExp',
                    data:dataListJson,
                    'contentType': 'application/json',
                    dataType: "json",
                    success: function (data) {
                        if (data.code = "success") {
                            toastr.success('消耗品入库成功');
                            layer.open({
                                title: "需要打印单据吗?",
                                type: 1,
                                area: ['300px', '150px'],
                                fixed: false, //不固定
                                skin: 'layui-layer-rim',
                                maxmin: true,
                                content:"",
                                btn: ['确定', '取消'],
                                yes: function (index, layero) {
                                    printPdf('${ctx}/csm/expDetails/expImportDetailsPrint?masterId='+data.data);
                                }, no: function (index) {
                                    layer.close(index);
                                }
                            });
                            loadDiv('mainCenterDiv','${ctx}/csm/expStock/index');
                            totalPrice();
                        } else {
                            alert("error");
                        }
                    },
                    error: function (data) {
                        toastr.error('网络连接错误,请检查网络');
                    }
                });
            }
        }
    }
</script>